<template>
  <div class="production-orders">
    <el-card class="header-card">
      <div class="page-header">
        <div class="header-left">
          <h2>
            <el-icon><Document /></el-icon>
            生产订单管理
          </h2>
          <p>管理生产订单，跟踪订单执行情况</p>
        </div>
        <div class="header-right">
          <el-button type="primary" @click="showAddDialog">
            <el-icon><Plus /></el-icon>
            新建生产订单
          </el-button>
          <el-button type="success" @click="handleImport">
            <el-icon><Upload /></el-icon>
            导入订单
          </el-button>
          <el-button @click="handleExport">
            <el-icon><Download /></el-icon>
            导出数据
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 搜索筛选 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="订单编号">
          <el-input v-model="searchForm.orderNo" placeholder="请输入订单编号" clearable />
        </el-form-item>
        <el-form-item label="产品名称">
          <el-input v-model="searchForm.productName" placeholder="请输入产品名称" clearable />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="待下发" value="pending" />
            <el-option label="生产中" value="producing" />
            <el-option label="已完成" value="completed" />
            <el-option label="已暂停" value="paused" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="紧急程度">
          <el-select v-model="searchForm.urgency" placeholder="请选择" clearable>
            <el-option label="正常" value="normal" />
            <el-option label="加急" value="urgent" />
            <el-option label="特急" value="critical" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><RefreshLeft /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <div class="statistics-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%)">
                <el-icon><DocumentCopy /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ statistics.total }}</div>
                <div class="stat-label">总订单数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%)">
                <el-icon><Operation /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ statistics.producing }}</div>
                <div class="stat-label">生产中</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)">
                <el-icon><Select /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ statistics.completed }}</div>
                <div class="stat-label">已完成</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon" style="background: linear-gradient(135deg, #fa709a 0%, #fee140 100%)">
                <el-icon><WarningFilled /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ statistics.urgent }}</div>
                <div class="stat-label">加急订单</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table :data="tableData" stripe border v-loading="loading" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="orderNo" label="订单编号" width="180" fixed>
          <template #default="{ row }">
            <el-link type="primary" @click="handleView(row)">{{ row.orderNo }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="productName" label="产品名称" min-width="200" />
        <el-table-column prop="productCode" label="产品编码" width="150" />
        <el-table-column prop="orderQty" label="订单数量" width="120" align="right">
          <template #default="{ row }">
            <el-tag>{{ row.orderQty }} {{ row.unit }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="completedQty" label="完成数量" width="120" align="right">
          <template #default="{ row }">
            <span :style="{ color: row.completedQty >= row.orderQty ? '#67c23a' : '#e6a23c' }">
              {{ row.completedQty }} {{ row.unit }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="completionRate" label="完成率" width="150">
          <template #default="{ row }">
            <el-progress :percentage="row.completionRate" :color="getProgressColor(row.completionRate)" />
          </template>
        </el-table-column>
        <el-table-column prop="urgency" label="紧急程度" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getUrgencyType(row.urgency)">{{ getUrgencyText(row.urgency) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="deliveryDate" label="交货日期" width="120" />
        <el-table-column prop="creator" label="创建人" width="100" />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="handleView(row)">
              <el-icon><View /></el-icon> 查看
            </el-button>
            <el-button link type="success" size="small" @click="handleStart(row)" v-if="row.status === 'pending'">
              <el-icon><VideoPlay /></el-icon> 下发
            </el-button>
            <el-button link type="warning" size="small" @click="handlePause(row)" v-if="row.status === 'producing'">
              <el-icon><VideoPause /></el-icon> 暂停
            </el-button>
            <el-button link type="primary" size="small" @click="handleEdit(row)" v-if="row.status === 'pending'">
              <el-icon><Edit /></el-icon> 编辑
            </el-button>
            <el-button link type="danger" size="small" @click="handleDelete(row)" v-if="row.status === 'pending'">
              <el-icon><Delete /></el-icon> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        class="pagination"
      />
    </el-card>

    <!-- 新建/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="1000px"
      @close="handleDialogClose"
    >
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="120px">
        <el-divider content-position="left">基本信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="订单编号" prop="orderNo">
              <el-input v-model="formData.orderNo" placeholder="自动生成" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="关联计划" prop="planId">
              <el-select v-model="formData.planId" placeholder="请选择生产计划" filterable>
                <el-option label="PLAN202501001" value="1" />
                <el-option label="PLAN202501002" value="2" />
                <el-option label="PLAN202501003" value="3" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="紧急程度" prop="urgency">
              <el-select v-model="formData.urgency" placeholder="请选择">
                <el-option label="正常" value="normal" />
                <el-option label="加急" value="urgent" />
                <el-option label="特急" value="critical" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">产品信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品名称" prop="productId">
              <el-select v-model="formData.productId" placeholder="请选择产品" filterable style="width: 100%">
                <el-option label="产品A" value="1" />
                <el-option label="产品B" value="2" />
                <el-option label="产品C" value="3" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订单数量" prop="orderQty">
              <el-input-number v-model="formData.orderQty" :min="1" :step="1" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">生产安排</el-divider>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="生产车间" prop="workshopId">
              <el-select v-model="formData.workshopId" placeholder="请选择车间">
                <el-option label="第一车间" value="1" />
                <el-option label="第二车间" value="2" />
                <el-option label="第三车间" value="3" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="生产线" prop="productionLine">
              <el-select v-model="formData.productionLine" placeholder="请选择生产线">
                <el-option label="A线" value="A" />
                <el-option label="B线" value="B" />
                <el-option label="C线" value="C" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="班次" prop="shift">
              <el-select v-model="formData.shift" placeholder="请选择班次">
                <el-option label="早班" value="morning" />
                <el-option label="中班" value="afternoon" />
                <el-option label="晚班" value="night" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="计划开始" prop="startDate">
              <el-date-picker
                v-model="formData.startDate"
                type="datetime"
                placeholder="选择开始时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交货日期" prop="deliveryDate">
              <el-date-picker
                v-model="formData.deliveryDate"
                type="date"
                placeholder="选择交货日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Document, Plus, Upload, Download, Search, RefreshLeft,
  DocumentCopy, Operation, Select, WarningFilled,
  View, VideoPlay, VideoPause, Edit, Delete
} from '@element-plus/icons-vue'

// 搜索表单
const searchForm = reactive({
  orderNo: '',
  productName: '',
  status: '',
  urgency: ''
})

// 统计数据
const statistics = reactive({
  total: 245,
  producing: 56,
  completed: 178,
  urgent: 11
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const selectedRows = ref([])

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('新建生产订单')
const formRef = ref(null)

// 表单数据
const formData = reactive({
  orderNo: '',
  planId: '',
  urgency: 'normal',
  productId: '',
  orderQty: 1,
  workshopId: '',
  productionLine: '',
  shift: '',
  startDate: '',
  deliveryDate: '',
  remark: ''
})

// 表单验证规则
const formRules = {
  productId: [{ required: true, message: '请选择产品', trigger: 'change' }],
  orderQty: [{ required: true, message: '请输入订单数量', trigger: 'blur' }],
  workshopId: [{ required: true, message: '请选择生产车间', trigger: 'change' }],
  startDate: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  deliveryDate: [{ required: true, message: '请选择交货日期', trigger: 'change' }]
}

// 获取表格数据
const fetchData = () => {
  loading.value = true
  setTimeout(() => {
    tableData.value = [
      {
        id: '1',
        orderNo: 'MO202501001',
        productName: '产品A型号1',
        productCode: 'PA-001',
        orderQty: 500,
        completedQty: 325,
        completionRate: 65,
        unit: '件',
        urgency: 'normal',
        status: 'producing',
        deliveryDate: '2025-01-20',
        creator: '张三'
      },
      {
        id: '2',
        orderNo: 'MO202501002',
        productName: '产品B型号2',
        productCode: 'PB-002',
        orderQty: 300,
        completedQty: 300,
        completionRate: 100,
        unit: '件',
        urgency: 'urgent',
        status: 'completed',
        deliveryDate: '2025-01-15',
        creator: '李四'
      },
      {
        id: '3',
        orderNo: 'MO202501003',
        productName: '产品C型号3',
        productCode: 'PC-003',
        orderQty: 800,
        completedQty: 0,
        completionRate: 0,
        unit: '件',
        urgency: 'critical',
        status: 'pending',
        deliveryDate: '2025-01-25',
        creator: '王五'
      }
    ]
    pagination.total = 3
    loading.value = false
  }, 500)
}

// 进度颜色
const getProgressColor = (percentage) => {
  if (percentage < 30) return '#f56c6c'
  if (percentage < 70) return '#e6a23c'
  return '#67c23a'
}

// 紧急程度类型
const getUrgencyType = (urgency) => {
  const types = {
    normal: '',
    urgent: 'warning',
    critical: 'danger'
  }
  return types[urgency] || ''
}

// 紧急程度文本
const getUrgencyText = (urgency) => {
  const texts = {
    normal: '正常',
    urgent: '加急',
    critical: '特急'
  }
  return texts[urgency] || urgency
}

// 状态类型
const getStatusType = (status) => {
  const types = {
    pending: 'info',
    producing: 'primary',
    completed: 'success',
    paused: 'warning',
    cancelled: 'danger'
  }
  return types[status] || 'info'
}

// 状态文本
const getStatusText = (status) => {
  const texts = {
    pending: '待下发',
    producing: '生产中',
    completed: '已完成',
    paused: '已暂停',
    cancelled: '已取消'
  }
  return texts[status] || status
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchData()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    orderNo: '',
    productName: '',
    status: '',
    urgency: ''
  })
  handleSearch()
}

// 表格选择
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 分页
const handleSizeChange = (size) => {
  pagination.size = size
  fetchData()
}

const handlePageChange = (page) => {
  pagination.page = page
  fetchData()
}

// 显示新建对话框
const showAddDialog = () => {
  dialogTitle.value = '新建生产订单'
  Object.assign(formData, {
    orderNo: 'MO' + Date.now(),
    planId: '',
    urgency: 'normal',
    productId: '',
    orderQty: 1,
    workshopId: '',
    productionLine: '',
    shift: '',
    startDate: '',
    deliveryDate: '',
    remark: ''
  })
  dialogVisible.value = true
}

// 查看
const handleView = (row) => {
  ElMessage.info('查看订单详情：' + row.orderNo)
}

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑生产订单'
  Object.assign(formData, row)
  dialogVisible.value = true
}

// 下发
const handleStart = (row) => {
  ElMessageBox.confirm('确定下发该生产订单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('下发成功')
    fetchData()
  })
}

// 暂停
const handlePause = (row) => {
  ElMessageBox.confirm('确定暂停该生产订单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('已暂停')
    fetchData()
  })
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确定删除该生产订单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
    fetchData()
  })
}

// 导入
const handleImport = () => {
  ElMessage.info('导入功能')
}

// 导出
const handleExport = () => {
  ElMessage.info('导出功能')
}

// 提交表单
const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      ElMessage.success('保存成功')
      dialogVisible.value = false
      fetchData()
    }
  })
}

// 关闭对话框
const handleDialogClose = () => {
  formRef.value?.resetFields()
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped lang="scss">
.production-orders {
  padding: 20px;

  .header-card {
    margin-bottom: 20px;
    
    .page-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .header-left {
        h2 {
          display: flex;
          align-items: center;
          gap: 10px;
          margin: 0 0 10px 0;
          font-size: 24px;
          color: #303133;
        }

        p {
          margin: 0;
          color: #909399;
          font-size: 14px;
        }
      }

      .header-right {
        display: flex;
        gap: 10px;
      }
    }
  }

  .filter-card {
    margin-bottom: 20px;
  }

  .statistics-cards {
    margin-bottom: 20px;

    .stat-card {
      .stat-content {
        display: flex;
        align-items: center;
        gap: 20px;

        .stat-icon {
          width: 60px;
          height: 60px;
          border-radius: 12px;
          display: flex;
          align-items: center;
          justify-content: center;
          color: white;
          font-size: 28px;
        }

        .stat-info {
          flex: 1;

          .stat-value {
            font-size: 28px;
            font-weight: bold;
            color: #303133;
            margin-bottom: 5px;
          }

          .stat-label {
            font-size: 14px;
            color: #909399;
          }
        }
      }
    }
  }

  .table-card {
    .pagination {
      margin-top: 20px;
      justify-content: flex-end;
    }
  }
}
</style>

